<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>分析结果 - SimpleHire</title>
  <link
          th:href="@{/webjars/bootstrap/5.3.0/css/bootstrap.min.css}"
          rel="stylesheet"
  />
  <style>
    .analysis-result {
      white-space: pre-wrap;
      line-height: 1.6;
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
    }
    .section {
      margin-bottom: 2rem;
      padding: 1rem;
      border-left: 4px solid #0d6efd;
      background-color: #f8f9fa;
    }
    .section h5 {
      color: #0d6efd;
      margin-bottom: 1rem;
    }
    .conversation-container {
      max-height: 400px;
      overflow-y: auto;
      border: 1px solid #dee2e6;
      border-radius: 5px;
      padding: 15px;
      margin-bottom: 15px;
      background-color: #f8f9fa;
    }
    .message {
      margin-bottom: 10px;
      padding: 10px;
      border-radius: 10px;
    }
    .user-message {
      background-color: #d1ecf1;
      margin-left: 20%;
      text-align: right;
    }
    .ai-message {
      background-color: #e2e3e5;
      margin-right: 20%;
    }
    .conversation-input {
      display: flex;
      gap: 10px;
    }
    .model-selector {
      min-width: 150px;
    }
  </style>
</head>
<body>
<div th:replace="fragments/header :: header"></div>

<main class="container mt-4">
  <div class="row">
    <div class="col-md-10 mx-auto">
      <div class="card">
        <div class="card-header bg-primary text-white">
          <h3>简历分析结果</h3>
        </div>
        <div class="card-body">
          <!-- 分析结果部分 -->
          <div th:if="${analysis}">
            <div class="analysis-result" th:utext="${analysis}"></div>
          </div>

          <hr th:if="${conversationActive}">

          <!-- 对话部分 -->
          <div th:if="${conversationActive}">
            <h5>AI面试对话</h5>

            <!-- 对话历史 -->
            <div class="conversation-container" id="conversationHistory">
              <div th:if="${conversationHistory}" th:utext="${conversationHistory}"></div>
              <div th:unless="${conversationHistory}" class="text-muted">
                对话尚未开始，请输入消息开始与AI面试官交流...
              </div>
            </div>

            <!-- 对话输入（新增模型选择下拉框） -->
            <div class="conversation-input">
              <select class="form-select model-selector" id="modelSelector">
                <option th:each="model : ${models}"
                        th:value="${model}"
                        th:text="${model}"
                        th:selected="${model == selectedModel}">
                </option>
              </select>
              <input type="text" class="form-control" id="userMessage"
                     placeholder="输入您的消息..." onkeypress="handleKeyPress(event)">
              <button class="btn btn-primary" onclick="sendMessage()">发送</button>
            </div>
          </div>

          <div class="mt-4">
            <a th:href="@{/interview}" class="btn btn-primary"
            >分析另一份简历</a
            >
            <a th:href="@{/dashboard}" class="btn btn-secondary"
            >返回仪表板</a
            >
          </div>
        </div>
      </div>
    </div>
  </div>
</main>

<div th:replace="fragments/footer :: footer"></div>

<script
        th:src="@{/webjars/bootstrap/5.3.0/js/bootstrap.bundle.min.js}"
></script>
<script>
  const interviewId = [[${interviewId}]];
  const defaultModel = [[${selectedModel}]];

  function sendMessage() {
      const messageInput = document.getElementById('userMessage');
      const modelSelector = document.getElementById('modelSelector');
      const message = messageInput.value.trim();
      const selectedModel = modelSelector.value;

      if (!message) return;

      // 添加用户消息到对话历史
      addMessage('我', message);
      messageInput.value = '';

      // 显示加载状态（显示当前选中的模型名称）
      const loadingDiv = document.createElement('div');
      loadingDiv.id = 'loading';
      loadingDiv.className = 'message ai-message';
      loadingDiv.innerHTML = `<strong>${selectedModel}面试辅助:</strong><br>思考中...`;
      document.getElementById('conversationHistory').appendChild(loadingDiv);
      scrollToBottom();

      // 发送到服务器（包含模型参数）
      fetch('/interview/conversation', {
          method: 'POST',
          headers: {
              'Content-Type': 'application/json',
          },
          body: JSON.stringify({
              message: message,
              interviewId: interviewId,
              model: selectedModel  // 传递选中的模型
          })
      })
      .then(response => {
          if (!response.ok) {
              throw new Error('网络响应不正常: ' + response.status);
          }
          return response.json();
      })
      .then(data => {
          // 移除加载状态
          const loadingElement = document.getElementById('loading');
          if (loadingElement) {
              loadingElement.remove();
          }

          if (data.success) {
              // 添加AI回复到对话历史（显示模型名称）
              addMessage(`${data.model}面试辅助`, data.message);
          } else {
              addMessage('系统', '错误: ' + data.message);
          }
          scrollToBottom();
      })
      .catch(error => {
          // 移除加载状态
          const loadingElement = document.getElementById('loading');
          if (loadingElement) {
              loadingElement.remove();
          }

          console.error('Error:', error);
          addMessage('系统', '网络错误: ' + error.message);
          scrollToBottom();
      });
  }

  function addMessage(sender, message) {
      const conversationDiv = document.getElementById('conversationHistory');
      const messageDiv = document.createElement('div');
      messageDiv.className = `message ${sender === '我' ? 'user-message' : 'ai-message'}`;
      messageDiv.innerHTML = `<strong>${sender}:</strong><br>${message}`;
      conversationDiv.appendChild(messageDiv);
      scrollToBottom();
  }

  function scrollToBottom() {
      const conversationDiv = document.getElementById('conversationHistory');
      conversationDiv.scrollTop = conversationDiv.scrollHeight;
  }

  function handleKeyPress(event) {
      if (event.key === 'Enter') {
          sendMessage();
          event.preventDefault();
      }
  }

  // 初始化时滚动到底部
  document.addEventListener('DOMContentLoaded', scrollToBottom);
</script>
</body>
</html>